package parsing

import (
	"fmt"
	"log"
	"strconv"
	"strings"

	"smartconn.cc/tosone/parsing/check"
	"smartconn.cc/tosone/parsing/handler"
	"smartconn.cc/tosone/parsing/model"
	"smartconn.cc/tosone/ra_main/ledutil"
)

var selected []string

var modelsOptions model.ModelsOptions

func init() {
	selected = []string{}
	modelsOptions = model.ModelsOptions{NetworkStatus: true}
}

// reset 重置
func reset() {
	selected = []string{}
}

// Start 开始 parsing
func Start(dir string, manifestStr string) {
	reset()
	if dir == "" {
		fmt.Println("Parsing: Story path is a blank directory.")
		return
	}
	modelsOptions.Predir = dir
	pages := strings.Split(manifestStr, "\n")
	totalPage := len(pages)

	handlers := handler.Index()
	pats := check.Pattern()
	checks := check.Check()
	ledutil.Green()
	flag := true
	for index := 0; index < totalPage; index++ {
		temp := 0
		flag = true
		for mode, pat := range pats {
			temp++
			patResult := pat.FindAllStringSubmatch(pages[index], 1)
			if len(patResult) == 1 {
				flag = false
				log.Println("Line " + strconv.Itoa(index+1) + ": mode is " + mode + ".")
				request := checks[mode](patResult[0])
				if flagTest(request.Flag) {
					response := handlers[mode](request, modelsOptions)
					selected = append(selected, response.Sound...)
				} else {
					fmt.Println("Line " + strconv.Itoa(index+1) + " has been jumped.")
				}
				break
			}
		}
		if temp == len(pats) && flag {
			if pages[index] == "" {
				log.Println("Line " + strconv.Itoa(index+1) + ": mode is blank.")
			} else {
				log.Println("Line " + strconv.Itoa(index+1) + ": mode is none.")
			}
		}
	}
	stopped()
}

// flagTest 检查当前的 flag 是否在已经播放的列表中
func flagTest(flag string) bool {
	if flag == "" {
		return true
	}
	for _, v := range selected {
		if flag == v {
			return true
		}
	}
	return false
}

// Stop 结束 parsing
func Stop() {
	handler.Stop()
	stopped()
}

func stopped() {
	ledutil.Close()
	log.Println("parsing over.")
	return
}
